package org.ubc.cs410.disposal2020.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class ServletUtils {

	public static void renderTemplate(ServletContext servletContext,
			Map<String, Object> root, String template,
			HttpServletResponse resp, String url) throws IOException {
		// Check for login status
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		if (user != null) {
			root.put("loggedIn", true);
			root.put("logoutUrl", userService.createLogoutURL(url));
		} else {
			root.put("loggedIn", false);
			root.put("loginUrl", userService.createLoginURL(url));
		}

		// Actual rendering
		Configuration config = ConfigFactory.get(servletContext);
		Template temp = config.getTemplate(template);
		PrintWriter out = resp.getWriter();
		try {
			temp.process(root, out);
			out.flush();
		} catch (TemplateException e) {
			e.printStackTrace(out);
		}
	}

}
